//
//  DashboardViewController.m
//  BMS
//
//  Created by 颜魏 on 2024/12/9.
//

#import "DashboardViewController.h"
#import "StatusCollectionViewCell.h"
#import "BTManager.h"

@interface DashboardViewController ()

@property (weak, nonatomic) IBOutlet UIView *leftPointBgView;
@property (weak, nonatomic) IBOutlet UIView *rightPointBgView;

@property (weak, nonatomic) IBOutlet UILabel *voltageLabel;     //电压
@property (weak, nonatomic) IBOutlet UILabel *electricCurrentLabel;     //电流

@property (weak, nonatomic) IBOutlet UILabel *statusTitleLabel;  //状态
@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;

@property (weak, nonatomic) IBOutlet UILabel *temperatureTitleLabel;    //温度
@property (weak, nonatomic) IBOutlet UILabel *temperatureLabel;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *temperatureWidth;

@property (weak, nonatomic) IBOutlet UILabel *cycleLifeTitleLabel;
@property (weak, nonatomic) IBOutlet UILabel *cycleLifeMinLabel;
@property (weak, nonatomic) IBOutlet UILabel *cycleLifeMaxLabel;
@property (weak, nonatomic) IBOutlet UILabel *cycleLifeCurrentLabel;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *cycleLifeWidth;
@property (weak, nonatomic) IBOutlet UILabel *cyclesTitleLabel;
@property (strong, nonatomic) IBOutletCollection(UIView) NSArray *shadowBgView;
@property (weak, nonatomic) IBOutlet UILabel *currentTagLabel;


@property (nonatomic, assign) CGFloat    voltage;       //电压
@property (nonatomic, assign) CGFloat    current;       //电流
@property (nonatomic, assign) NSInteger  templerature;  //温度
@property (nonatomic, assign) NSInteger  cycles;        //循环次数

@property (nonatomic, assign) NSInteger cbcDSG;     //CBC_DSG异常标志

@property (nonatomic, assign) NSInteger preMOS;     //预充MOS管
@property (nonatomic, assign) NSInteger chgMOS;     //充电MOS管
@property (nonatomic, assign) NSInteger dsgMOS;     //放电MOS管
@property (nonatomic, assign) NSInteger preRelay;   //预充继电器
@property (nonatomic, assign) NSInteger chgRelay;   //分口充电继电器
@property (nonatomic, assign) NSInteger dsgRelay;   //分口放电继电器
@property (nonatomic, assign) NSInteger mainRelay;  //同口主继电器

@property (nonatomic, strong) NSArray   *normalIcons;   //错误图标
@property (nonatomic, strong) NSArray   *selectIcons;   //正常图标
@property (nonatomic, strong) NSArray   *titles;        //items
@property (nonatomic, strong) NSMutableArray *status;   //正常状态

@property (nonatomic, assign) BOOL isFull;

@end

@implementation DashboardViewController

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didReciveData:) name:kBTDidReciveData object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didReciveSOCData:) name:kBTSOCData object:nil];

    self.normalIcons = @[@"status_icon_n_1", @"status_icon_n_2", @"status_icon_n_3", @"status_icon_n_7", @"status_icon_n_5", @"status_icon_n_6", @"status_icon_n_8", @"status_icon_n_4"];
    self.selectIcons = @[@"status_icon_1", @"status_icon_2", @"status_icon_3", @"status_icon_7", @"status_icon_5", @"status_icon_6", @"status_icon_8", @"status_icon_4"];
    self.titles = @[@"Standby", @"Discharging", @"Charging", @"Full", @"Over\nCurrent", @"Over\nTemp", @"Under\nVoltage", @"Short\nCircuit"];
    self.status = [[NSMutableArray alloc] initWithArray:@[@YES, @NO, @NO, @NO, @NO, @NO, @NO, @NO]];

    self.leftPointBgView.transform = CGAffineTransformRotate(self.leftPointBgView.transform, M_PI_2/4.0*0);
    self.rightPointBgView.transform = CGAffineTransformRotate(self.rightPointBgView.transform, M_PI_2/4.0*0);

    for (UIView *v in self.shadowBgView) {
        v.layer.shadowColor = [UIColor lightGrayColor].CGColor;
        v.layer.shadowOffset = CGSizeMake(0, 3);
        v.layer.shadowOpacity = 0.7;
        v.layer.shadowRadius = 5;
    }
    self.currentTagLabel.text = NSLocalizedString(@"Current",nil);

    [self setLanguage];
    self.temperatureWidth.constant = 30*((kWidth-110)/130.0);

    [self.collectionView registerNib:[UINib nibWithNibName:@"StatusCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"StatusCollectionViewCell"];
}

- (void)setLanguage {
    self.statusTitleLabel.text = NSLocalizedString(@"Status",nil);
    self.temperatureTitleLabel.text = NSLocalizedString(@"Temperature",nil);
    self.cycleLifeTitleLabel.text = NSLocalizedString(@"Cycle Life",nil);
    self.cyclesTitleLabel.text = NSLocalizedString(@"Cycles",nil);
}

- (void)updateUI {
    self.voltageLabel.text = [NSString stringWithFormat:@"%.2fV", self.voltage];
    self.electricCurrentLabel.text = [NSString stringWithFormat:@"%.2fA", self.current];
    self.temperatureLabel.text = [NSString stringWithFormat:@"%ld", (long)self.templerature];
    self.cycleLifeCurrentLabel.text = [NSString stringWithFormat:@"%ld", (long)self.cycles];
    self.cycleLifeWidth.constant = self.cycles*((kWidth-110)/8000.0)<15 ? 15 : self.cycles*((kWidth-110)/8000.0);
    CGFloat temp = self.templerature;
    if (temp<0) {
        temp = -temp;
    }else {
        temp += 30;
    }
    self.temperatureWidth.constant = temp*((kWidth-110)/130.0);

    CGFloat leftRato = self.voltage/6.0;
    if (self.voltage>60) {
        leftRato = 10;
    }
    self.leftPointBgView.transform = CGAffineTransformMakeRotation(M_PI_2/4.0*leftRato);
    CGFloat rightRato = self.current/20.0;
    if (self.current>200) {
        rightRato = 10;
    }
    self.rightPointBgView.transform = CGAffineTransformMakeRotation(M_PI_2/4.0*rightRato);
    
    [self.collectionView reloadData];
}

#pragma mark - notification
- (void)didReciveSOCData:(NSNotification *)notification {
    self.isFull = [notification.object boolValue];
}

- (void)didReciveData:(NSNotification *)notification {
    if ([BTManager sharedBTManager].isGettingBattery) return;
    NSData *reciveData = notification.object;
    Byte *dataBytes = (Byte*)reciveData.bytes;
    if (dataBytes[2]==0x2a) {
        //3.3 主控读取时钟及保护记录等信息
        //放电短路
        self.cbcDSG = dataBytes[3+0x13*2];
        NSInteger hardwareAlarm = self.preMOS + self.chgMOS + self.dsgMOS + self.preRelay + self.chgRelay + self.dsgRelay + self.mainRelay;
        [self.status replaceObjectAtIndex:3 withObject:@(self.cbcDSG>0&&hardwareAlarm==0)];
    }
    if (dataBytes[2]==0x18) {
        //主机读取电池其他信息 3.4
        NSInteger secondByte = dataBytes[4];
        //预充MOS管
        self.preMOS = (secondByte & 0x02) > 0 ? 1 : 0;
        //充电MOS管
        self.chgMOS = (secondByte & 0x04) > 0 ? 1 : 0;
        //放电MOS管
        self.dsgMOS = (secondByte & 0x08) > 0 ? 1 : 0;
        //预充继电器
        self.preRelay = (secondByte & 0x10) > 0 ? 1 : 0;
        //分口充电继电器
        self.chgRelay = (secondByte & 0x20) > 0 ? 1 : 0;
        //分口放电继电器
        self.dsgRelay = (secondByte & 0x40) > 0 ? 1 : 0;
        //同口主继电器
        self.mainRelay = (secondByte & 0x80) > 0 ? 1 : 0;
        NSInteger hardwareAlarm = self.preMOS + self.chgMOS + self.dsgMOS + self.preRelay + self.chgRelay + self.dsgRelay + self.mainRelay;
        [self.status replaceObjectAtIndex:3 withObject:@(self.cbcDSG>0&&hardwareAlarm==0)];
        
    }
    if ((dataBytes[2]==0x32) & (reciveData.length>30)) {
        //3.2 主控读取电池温度电流等信息
        //循环次数
        self.cycles = dataBytes[3+0x13*2]*256 + dataBytes[3+0x13*2+1];
        //最高温度
        self.templerature = dataBytes[3+0x0a*2]*256 + dataBytes[3+0x0a*2+1];
        self.templerature = (self.templerature-400)/10;
        
        //放电电流
        NSInteger disChargingCurrent = dataBytes[3+0xd*2]*256+dataBytes[3+0xd*2+1];
        [self.status replaceObjectAtIndex:1 withObject:@(disChargingCurrent>0)];
        //充电电流
        NSInteger chargingCurrent = dataBytes[3+0xc*2]*256+dataBytes[3+0xc*2+1];
        [self.status replaceObjectAtIndex:2 withObject:@(chargingCurrent>0)];
        //电流
        self.current = disChargingCurrent/10.0;
        if (chargingCurrent>0) self.current = chargingCurrent/10.0;
        //电池状态
        [self.status replaceObjectAtIndex:0 withObject:@(disChargingCurrent==0 && chargingCurrent==0)];
        
        NSInteger thirdSafeystatusSecondbyte = dataBytes[3+0x16*2+1];
        //充电过流
        NSInteger chargingCurrentExceed = (thirdSafeystatusSecondbyte & 0x10) > 0 ? 1 : 0;
        //放电过流
        NSInteger disChargingCurrentExceed = (thirdSafeystatusSecondbyte & 0x20) > 0 ? 1 : 0;
        [self.status replaceObjectAtIndex:4 withObject:@(chargingCurrentExceed>0 || disChargingCurrentExceed>0)];

        //充电过温
        NSInteger chargingCurrentExceedTemperature = (thirdSafeystatusSecondbyte & 0x40) > 0 ? 1 : 0;
        //放电过温
        NSInteger disChargingCurrentExceedTemperature = (thirdSafeystatusSecondbyte & 0x80) > 0 ? 1 : 0;
        [self.status replaceObjectAtIndex:5 withObject:@(chargingCurrentExceedTemperature>0 || disChargingCurrentExceedTemperature>0)];

        NSInteger soc = dataBytes[3 + 0x0e * 2] * 256 + dataBytes[3 + 0x0e * 2 + 1]; //SOC
        [self.status replaceObjectAtIndex:6 withObject:@(soc>=100)];
        
//        //单节过压
//        NSInteger voltageSingleExceed = (thirdSafeystatusSecondbyte & 0x01) > 0 ? 1 : 0;
//        //总压过压
//        NSInteger voltageTotalExceed = (thirdSafeystatusSecondbyte & 0x04) > 0 ? 1 : 0;
//        [self.status replaceObjectAtIndex:6 withObject:@(voltageSingleExceed>0 || voltageTotalExceed>0)];

        //单节欠压
        NSInteger voltageSingleLower = (thirdSafeystatusSecondbyte & 0x02) > 0 ? 1 : 0;
        //总压欠压
        NSInteger voltageTotalLower = (thirdSafeystatusSecondbyte & 0x08) > 0 ? 1 : 0;
        [self.status replaceObjectAtIndex:7 withObject:@(voltageSingleLower>0 || voltageTotalLower>0)];
    }
    if (dataBytes[2]==0x4c) {
        //3.1 主控读取电池电压数据
        self.voltage = (float)(dataBytes[3+0x25*2]*256+dataBytes[3+0x25*2+1]);
        self.voltage = self.voltage / 100;
    }
    
    [self updateUI];
}

#pragma mark - UICollectionViewDelegate
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.status.count;
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    StatusCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"StatusCollectionViewCell" forIndexPath:indexPath];
    cell.title = NSLocalizedString(self.titles[indexPath.row], nil);
    NSMutableArray *sts = [NSMutableArray arrayWithArray:self.status];
    [sts exchangeObjectAtIndex:3 withObjectAtIndex:6];
    [sts exchangeObjectAtIndex:6 withObjectAtIndex:7];
    BOOL state = [sts[indexPath.row] boolValue];
    if (indexPath.item == 3) {
        if (self.isFull) {
            state = YES;
        }
    }
    cell.isStandby = state;
    cell.iconImage = state ? self.selectIcons[indexPath.row] : self.normalIcons[indexPath.row];
    cell.index = indexPath.row;

    return cell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    return CGSizeMake((kWidth-40-1-15)/4.0, 75);
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
    return 5;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
    return 5;
}


@end
